package blt.app_core.api.impl;

import android.content.Context;

import java.lang.reflect.ParameterizedType;
import java.util.concurrent.TimeUnit;

import blt.app_core.api.base.CoreManager;
import blt.app_core.api.base.IBaseApi;
import blt.app_core.api.base.ICoreClient;
import blt.app_core.api.base.LoginInterceptor;
import blt.app_core.api.message.MessageApi;
import blt.app_core.api.message.bean.WeatherInfo;
import blt.app_core.log.Logger;
import blt.app_core.utils.CacheUtil;
import blt.app_core.utils.UriProdiver;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.Url;

/**
 * retrofit 有严格的检查机制，在进行gson解析时如果数据结构对应错误，会导致没有响应返回
 * Created by xgp on 2017/6/17.
 */

public class BaseImpl<Service> implements IBaseApi {
    private static Retrofit mRetrofit;

    protected Service mService;
    private static OkHttpClient client;


    public BaseImpl() {
        initRetrofit();
        this.mService = mRetrofit.create(getServiceClass());
    }

    protected Context getContext() {
        return CoreManager.getContext();
    }

    protected void notifyClients(Class<? extends ICoreClient> clientClass, String methodName, Object... args) {
        CoreManager.notifyClients(clientClass, methodName, args);
    }


    /**
     * 封装公共参数和公共解析
     *
     * @return
     */

    public Class<Service> getServiceClass() {
        return (Class<Service>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    private void initRetrofit() {
        if (null != mRetrofit)
            return;

        // 设置 Log 拦截器，可以用于以后处理一些异常情况
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

            @Override
            public void log(String message) {

                Logger.e(message);
            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 配置 client
        client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)                // 设置拦截器
                .retryOnConnectionFailure(true)             // 是否重试
                .connectTimeout(5, TimeUnit.SECONDS)        // 连接超时事件
                .readTimeout(5, TimeUnit.SECONDS)           // 读取超时时间
//                .addNetworkInterceptor(mTokenInterceptor)   // 自动附加 token
//                .authenticator(mAuthenticator)              // 认证失败自动刷新token
                .build();

        // 配置 Retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(UriProdiver.BASE_URL)                         // 设置 base url
                .client(client)                                     // 设置 client
                .addConverterFactory(GsonConverterFactory.create()) // 设置 Json 转换工具
                .build();
    }


    /**
     * 首先通关登陆注册获取userId和cookie，然后缓存这2个参数，构建心的请求体
     */
    public void builderLoginRequest() {
        final String cookie = CacheUtil.getCache().getCookie();
        final String userId = CacheUtil.getCache().getUid();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//        Interceptor mInterceptor = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request originalRequest = chain.request();
//                Logger.d("userId:" + userId + "  cookie:" + cookie);
//                RequestBody body = new FormBody.Builder().add("userId", userId).build();
//                Request request = originalRequest.newBuilder()
//                        .header(COOKIE, cookie)
//                        .method(originalRequest.method(), originalRequest.body())
//                        .post(body)
//                        .build();
//                return chain.proceed(request);
//            }
//        };

        LoginInterceptor loginInterceptor = new LoginInterceptor(userId, cookie);

        client = new OkHttpClient.Builder().
                addInterceptor(loginInterceptor).addInterceptor(interceptor)
                .build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(UriProdiver.BASE_URL)                         // 设置 base url
                .client(client)                                     // 设置 client
                .addConverterFactory(GsonConverterFactory.create()) // 设置 Json 转换工具
                .build();
        this.mService = mRetrofit.create(getServiceClass());

    }

    /**
     * 针对不同的请求，做2组request，一组带登录信息，一组不带
     */


    public interface WeatherService {
        @GET
        Call<WeatherInfo> getWeather(@Url String url, @Query("key") String key, @Query("city") String city);
    }


    public void getBaseWeather(String city) {
        WeatherService service = mRetrofit.create(WeatherService.class);
        service.getWeather(UriProdiver.GET_WEATHER, UriProdiver.WEATHER_KEY, city).enqueue(new Callback<WeatherInfo>() {
            @Override
            public void onResponse(Call<WeatherInfo> call, retrofit2.Response<WeatherInfo> response) {
                if (response.isSuccessful()) {
                    WeatherInfo.Weather weather = response.body().HeWeather5.get(0);
//                    Logger.d("getWeather onResponse" + now.code);
                    notifyClients(MessageApi.class, MessageApi.onWeather, weather);
                }
            }

            @Override
            public void onFailure(Call<WeatherInfo> call, Throwable t) {

            }
        });
    }

}
